#!/bin/sh

#export PATH="/mnt/ESensor/bin:$PATH"

cfgAlarmConfPath="/mnt/ESensor/etc/alarm.conf"
cfgAlarmInConfPrefix="ALARM_OUT.DROPBOX"
#Default configuration file
CONFIG_FILE=/tmp/dropbox_uploader.conf

#Don't edit these...
API_REQUEST_TOKEN_URL="https://api.dropbox.com/1/oauth/request_token"
API_USER_AUTH_URL="https://www2.dropbox.com/1/oauth/authorize"
API_ACCESS_TOKEN_URL="https://api.dropbox.com/1/oauth/access_token"
APP_CREATE_URL="https://www2.dropbox.com/developers/apps"
RESPONSE_FILE="/tmp/du_resp_$RANDOM"

umask 077

#Returns unix timestamp
utime ()
{
    echo $(date +%s)
}

#Remove temporary files
remove_temp_files ()
{
    rm -fr $RESPONSE_FILE
}

# Read parameter form setting
APPKEY=$(sed -n -e 's/APPKEY:\([a-z A-Z 0-9]*\)/\1/p' "$CONFIG_FILE")
APPSECRET=$(sed -n -e 's/APPSECRET:\([a-z A-Z 0-9]*\)/\1/p' "$CONFIG_FILE")
OAUTH_TOKEN=$(sed -n -e 's/OAUTH_TOKEN:\([a-z A-Z 0-9]*\)/\1/p' "$CONFIG_FILE")
OAUTH_TOKEN_SECRET=$(sed -n -e 's/OAUTH_TOKEN_SECRET:\([a-z A-Z 0-9]*\)/\1/p' "$CONFIG_FILE")
        
#API_ACCESS_TOKEN_URL
time=$(utime)
/mnt/ESensor/bin/curl -s -k --show-error -i -o $RESPONSE_FILE --data "oauth_consumer_key=$APPKEY&oauth_token=$OAUTH_TOKEN&oauth_signature_method=PLAINTEXT&oauth_signature=$APPSECRET%26$OAUTH_TOKEN_SECRET&oauth_timestamp=$time&oauth_nonce=$RANDOM" "$API_ACCESS_TOKEN_URL"
OAUTH_ACCESS_TOKEN_SECRET=$(sed -n -e 's/oauth_token_secret=\([a-z A-Z 0-9]*\)&.*/\1/p' "$RESPONSE_FILE")
OAUTH_ACCESS_TOKEN=$(sed -n -e 's/.*oauth_token=\([a-z A-Z 0-9]*\)&.*/\1/p' "$RESPONSE_FILE")
OAUTH_ACCESS_UID=$(sed -n -e 's/.*uid=\([0-9]*\)/\1/p' "$RESPONSE_FILE")

cat  << EOF
Content-type: text/html

<html>
<head>
<script type="text/javascript">
EOF
if [ -n "$OAUTH_ACCESS_TOKEN" -a -n "$OAUTH_ACCESS_TOKEN_SECRET" -a -n "$OAUTH_ACCESS_UID" ]; then
	`/mnt/ESensor/bin/config -f $cfgAlarmConfPath -p $cfgAlarmInConfPrefix.[0].OAuthAccessToken -v $OAUTH_ACCESS_TOKEN`
	`/mnt/ESensor/bin/config -f $cfgAlarmConfPath -p $cfgAlarmInConfPrefix.[0].OAuthAccessTokenSecret -v $OAUTH_ACCESS_TOKEN_SECRET`
	
	echo "alert(\"Test passed.\nESensor has permission to upload files to your Dropbox space.\");"
else
	echo "alert(\"Test failed!\nPlease clcik \\\"1.Allow Access\\\" button to finish Dropbox authentication before testing.\");"
fi

cat << EOF
window.close();
</script>
</head>
</html>
EOF

remove_temp_files
sync
exit 0
